package com.lmt.ymcc.mq.listener;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.IService;
import com.lmt.ymcc.domain.PayOrder;
import com.lmt.ymcc.dto.AliPayMessageDto;
import com.lmt.ymcc.service.IPayNotifyService;
import com.lmt.ymcc.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;
import java.util.Map;


@RocketMQTransactionListener(txProducerGroup="TxPayAliNotifyGroup")
@Slf4j
public class AliPayTransMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayNotifyService payNotifyService;

    @Autowired
    private IPayOrderService payOrderService;

   // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        log.info("执行本地事务");
        if(arg == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        Map<String,Object> map = (Map<String,Object>) arg;
        try {
            //执行本地订单保存
            payNotifyService.updatePayOrderAndInsertFlow(map);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] body = (byte[]) message.getPayload();
            String jsonStr = new String(body, StandardCharsets.UTF_8);
            AliPayMessageDto aliPayMessageDto = JSONObject.parseObject(jsonStr, AliPayMessageDto.class);
            PayOrder payOrder = payOrderService.checkPayOrder(aliPayMessageDto.getOrderNo());
            if(payOrder != null && payOrder.getPayStatus() == PayOrder.STATE_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}